import java.util.Arrays;

public class HeapSort {

    public static void main(String[] args) {
        int[] arr = {9,8,7,6,5,4,3,2,1};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));


    }

    public static void heapSort(int[] arr) {
        int temp = 0;
        for(int i=arr.length/2 -1; i >= 0; i--) {
            adjustHeap(arr,i, arr.length);
        }

        for(int j = arr.length -1;j > 0; j--) {
            temp = arr[j];
            arr[j] = arr[0];
            arr[0] = temp;
            adjustHeap(arr, 0, j);
        }
    }

    /**
     *
     * @param arr
     * @param i   表示非叶子阶段在数组中的位置
     * @param length
     */
    private static void adjustHeap(int[] arr, int i, int length) {
        int temp = arr[i]; //非叶子节点
        //k = i*2 +1    k是i节点的左子节点
        for(int k = i*2 + 1; k<length; k= k*2 + 1) {
            if (k +1 < length && arr[k] < arr[k+1]) {
                k++;
            }
            if (arr[k] > arr[i]) {
                arr[i]= arr[k];
                i = k;
            }
        }

        arr[i] = temp;
    }
}
